<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\BaseAdminController;
use App\Lib\Common;
use App\Lib\Logger;
use App\Lib\Validates;
use App\Models\Admin\AdminUser;
use App\Rules\CheckRule;
use App\Service\AdminUserService;
use App\Service\AuthService;
use App\Service\OrgService;
use App\Service\SiteService;
use App\Service\UpLoad;
use ESCloud\SDK\Auth;
use Illuminate\Http\Request;
use App\Lib\Enum\ValRule;


class UserController extends BaseAdminController
{
    protected $adminUserService = "";
    protected $orgService = "";
    protected $authService = "";

    public function _init() {
        $this->adminUserService = new AdminUserService();
        $this->orgService = new OrgService("Admin.Org");
        $this->authService=new AuthService();
        $this->siteService=new SiteService("Admin.site");
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $params = $request->all();
        //获取用户
        $list = $this->adminUserService->list(array_key_exists("limit", $params) ? $params["limit"] : config("model.pagesize"), $params);
        $result = empty($list) ? $this->error(80000, "没有用户") : $this->success($list);
        //获取组织机构
        $orgs = $this->orgService->orgList([],["id","parent_id","name"]);
//        $orgs = $this->orgService->getAll(["id","parent_id","name"]);
        return view("admin.admin_user.index", ["error" => $result['error'], "user" => $result['data'], "search" => $params, "orgs" => json_encode(Common::getTree($orgs))]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        if($this->request->isMethod("get")){
            //获取组织机构
            $orgs = $this->orgService->getAll(["id","parent_id","name"]);
            return view('admin.admin_user.create', ["orgs" => json_encode(Common::getTree($orgs))]);
        }
        else{
            return $this->store($this->request);
        }

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected function store(Request $request) {
        //验证
        $result = (new CheckRule($request->all(), ValRule::USER_STORE, ValRule::USER_STORE_MSG))->check();
        if ($result["error"] == 0) {
            //添加
            $result = $this->adminUserService->register($result["data"]);
            if (!empty($result)) {
                $this->log(Logger::LOG_LEVEL_INFO,Logger::ADMIN_USER,'store','成功添加用户'.$result['name'],$result);
                return $this->success($result, "添加成功");
            }
            $this->log(Logger::LOG_LEVEL_ERROR,Logger::ADMIN_USER,'store','添加用户'.$result['name'].'失败',['error'=>70000]);
            return $this->error(70000, "添加失败");
        }
        return $this->error($result["error"], $result["msg"]);
    }

    /**
     * Display the specified resource.
     *
     * @param AdminUser $adminUser
     * @return \Illuminate\Http\Response
     */
    public function show(AdminUser $user) {
        //获取组织机构信息
        $org = $this->orgService->getInfo($user->org_id);
        //获取站点信息
        $site = $this->siteService->first(["id"=>$user->site_id]);
        return view("admin.admin_user.show", ["user" => $user, "site" => $site["name"], "org" => empty($org)?$org["name"]="尚未分配":$org["name"]]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param AdminUser $adminUser
     * @return \Illuminate\Http\Response
     */
    public function edit(AdminUser $user) {
        //获取组织机构
        $orgs = $this->orgService->orgList([]);
        //用户站点
        $sites = $this->adminUserService->selectSite();
        return view("admin.admin_user.edit", ["user" => $user, "sites" => $sites, "org_id" => $user->org_id, "orgs" => json_encode($orgs)]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice('admin.admin_user.index', "用户不存在", "error");
        }

        //更新
        $result = $this->adminUserService->updateInfo($request->all(), $id);
        if(!$result){
            $this->log(Logger::LOG_LEVEL_ERROR,Logger::ADMIN_USER,'update','更新用户编号为'.$id.'的信息失败',['error'=>80000]);
            return $this->error(80000, "更新失败");
        }
        $this->log(Logger::LOG_LEVEL_INFO,Logger::ADMIN_USER,'update','更新用户编号为'.$id.'的信息成功',[]);
        return  $this->success("", "更新成功");
    }

    /**
     * 上传图片
     */
    public function upload(Request $request) {
        $file = $request->file('imgup');
        $result = (new UpLoad())->up_img($file, config("storage.adminicon"));
        if ($result) {
            $this->log(Logger::LOG_LEVEL_INFO,'admin','upload','上传图片成功',[]);
            return $this->success(["path" => $result], "上传成功", 2);
        }
        $this->log(Logger::LOG_LEVEL_ERROR,'admin','upload','上传图片失败',['error'=>100000]);
        return $this->error(100000, "上传失败", 2, ["path" => $result]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {

    }

    /**
     * 开启/禁用
     * @param $id 禁用id
     */
    public function isOpen(Request $request) {
        $params = (new CheckRule($request->all(), ValRule::STATUS, ValRule::STATUS_MSG))->check();
        if ($params["error"] > 0) {
            return $this->error($params['error'], $params['msg'], 2);
        }
        //系统状态
        $is_system = (new AdminUser())->isSystem($params["data"]["id"]);
        //检查是否是自己或系统账号
        if (getCurrentUser()["id"] == $params["data"]["id"] || $is_system == 1) {
            return $this->error(70001, "不可以禁用自己或系统的账号", 2);
        }
        //启用开关
        $result = (new AdminUser())->onOrOff($params["data"]);
        if(!$result){
            $this->log(Logger::LOG_LEVEL_ERROR,Logger::ADMIN_USER,'isOpen','修改用户编号为'.$params['data']['id'].'的状态失败',['error'=>80000]);
            return $this->error(80000, "状态修改失败");
        }
        $this->log(Logger::LOG_LEVEL_INFO,Logger::ADMIN_USER,'isOpen','修改用户编号为'.$params['data']['id'].'的状态成功',[]);
        return $this->success("", "状态修改成功");
    }

    /**
     * 分配角色模板
     */
    public function role_form(AdminUser $user) {
        //获取角色
        $roles = $this->authService->get_roles();
        //用户已有角色
        $has_role = $this->authService->hasUserRoles($user);
        //用户已有分类
        $has_category=$this->authService->userHasCategory($user->id);
        //组织机构
        $orgs = $this->authService->getOrg($user->id);
        //读取过期时间
        $roles = $this->authService->getExpire($roles, $has_role);
        //获取分类数据
        $category = Common::getTree(getData("CategoryDataTag",["group_id"=>1]));
        return view("admin.admin_user.ass_role_form", ["user" => $user, "roles" => $roles, "has_role" => $has_role,"hasCategory"=>json_encode($has_category),"orgs"=>json_encode($orgs),"category"=>json_encode($category)]);
    }

    /**
     * 分配角色
     */
    public function assign(AdminUser $user, Request $request) {
        //验证
        $val = (new CheckRule($request->all(), ValRule::ASSIGN_ROLE, ValRule::ASSIGN_ROLE_MSG))->check();
        if ($val["error"] > 0) {
            return $this->error($val["error"],$val["msg"]);
        }
        //分配
        $result = (new AuthService())->assignRole($user, $val);
        if($result['error']>0){
            $this->log(Logger::LOG_LEVEL_ERROR,Logger::ADMIN_USER,'assign','给编号为'.$user->id.'用户分配权限，失败',$result);
            return $this->error($result["error"],$result["msg"]);
        }
        $this->log(Logger::LOG_LEVEL_INFO,Logger::ADMIN_USER,'assign','给编号为'.$user->id.'用户分配权限，成功',$result);
        return $this->success("", $result["msg"]);
    }

    /**
     * 修改密码
     */
    public function changePwdShow($user_id) {
        //验证
        $check = Validates::isPositiveInteger($user_id);
        if (!$check) {
            return $this->error(70000, "用户不存在");
        }
        return view("admin.admin_user.edit_pwd", ["user_id" => $user_id]);

    }

    public function changePwd($id, Request $request) {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->error(70000, "用户不存在");
        }
        $val = (new CheckRule($request->all(), ValRule::PWD_STORE, ValRule::PWD_STORE_MSG))->check();
        if ($val["error"] > 0) {
            return $this->tempNotice("admin.admin_user.edit_pwd", $val["msg"], "error");
        }
        //更新
        $result = $this->adminUserService->pwdEdit($id, $request->all());
        if($result){
            $this->log(Logger::LOG_LEVEL_INFO,Logger::ADMIN_USER,'changePwd','修改了用户编号为'.$id.'的密码，修改成功',['error'=>$val["error"]]);
            return $this->success("", "修改成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR,Logger::ADMIN_USER,'changePwd','修改了用户编号为'.$id.'的密码，修改失败',['error'=>200000]);
        return $this->error(200000, "修改失败");
    }
}
